<template>
    <div class="card mt-3">
        <div class="card-header d-flex justify-content-between align-items-center">
            <div class="filter-group">
                <img src="/src/assets/icon/icon_filter.svg" alt="filter" class="filter-btn"
                    @click="showFilterCheckBox = !showFilterCheckBox">
                <Transition name="fade">
                    <div v-if="showFilterCheckBox" class="filter-menu form-check">
                        <div v-for="item in ['全部', '收入', '支出']" class="filter-item">
                            <input type="radio" name="filter" class="form-check-input" :value="item" v-model="filter" />
                            <label>{{ item }}</label>
                        </div>
                    </div>
                </Transition>
            </div>
            <div v-if="!isEditing" class="search-group">
                <input type="text" class="form-control" placeholder="搜索任意内容" v-model="searchStr">
            </div>
            <span v-if="isEditing">双击可以编辑内容</span>
            <div>
                <button v-if="isEditing" type="button" name="deleteCheckedBtn"
                    class="edit-col btn btn-danger btn-sm mx-2" @click="deleteChecked"
                    :disabled="checkedCount == 0">删除多选</button>
                <button id="edit-btn" name="edit-btn" @click="isEditing = !isEditing" class="btn btn-sm"
                    :class="isEditing ? 'btn-dark' : 'btn-secondary'">{{ isEditing ? '退出' : '编辑' }}</button>
            </div>
        </div>
        <div class="card-body">
            <table class="table" id="billTable">
                <thead>
                    <tr>
                        <th v-if="isEditing" scope="col" class="text-start edit-col col-1">
                            <input title="全选" class="form-check-input" type="checkbox" id="checkAll" name="selectAll"
                                @click="checkAll" :checked="checkedCount == billList.length">
                        </th>
                        <!-- <th scope="col" class="col-1">#</th> -->
                        <!-- <th scope="col">类型</th> -->
                        <th scope="col" class="col-2 sort-col" @click="changeSort('date')">
                            <SortThead title="日期" :sorting="sortField === 'date' ? this.collation : ''" />
                        </th>
                        <th scope="col" class="col-3"><span>描述</span></th>
                        <th scope="col" class="col-4">备注</th>
                        <th scope="col" class="col-1 sort-col" @click="changeSort('amount')">
                            <SortThead title="金额" :sorting="sortField === 'amount' ? this.collation : ''" />
                        </th>
                        <td v-if="isEditing" scope="col" class="text-end edit-col col-2">
                        </td>
                    </tr>
                </thead>
                <tbody v-if="!showLoading">
                    <tr v-for="bill, index in searchByAny" :key="bill.id" class="myhover"
                        @keyup.enter.stop="edit_done()" :class="bill.type == 1 ? 'table-danger' : 'table-success'">
                        <td v-if="isEditing" scope="col" class="edit-col">
                            <input title="选择" class="form-check-input checkItem" type="checkbox" name="checkItem"
                                v-model="bill.isChecked">
                        </td>
                        <!-- <td scope="row">{{ index + 1 }}</td> -->
                        <!-- <td scope="row">{{ bill.type }}</td> -->
                        <td scope="row">{{ bill.date }}</td>
                        <td scope="row" @dblclick="handleDoubleClick(bill, 1)">
                            <span v-if="!(isEditing && editingView.bill == bill && editingView.index == 1)">
                                {{ bill.resume }}</span>
                            <input v-if="isEditing && editingView.bill == bill && editingView.index == 1"
                                class="edit-input" @blur="edit_done()" v-model="bill.resume" />
                        </td>
                        <td scope="row" @dblclick="handleDoubleClick(bill, 2)">
                            <span v-if="!(isEditing && editingView.bill == bill && editingView.index == 2)">
                                {{ bill.description }}</span>
                            <input v-if="isEditing && editingView.bill == bill && editingView.index == 2"
                                class="edit-input" @blur="edit_done()" v-model="bill.description" />
                        </td>
                        <td scope="row" @dblclick="handleDoubleClick(bill, 3)">
                            <span v-if="!(isEditing && editingView.bill == bill && editingView.index == 3)">
                                {{ bill.amount }}</span>
                            <input v-if="isEditing && editingView.bill == bill && editingView.index == 3"
                                class="edit-input col-1" @blur="edit_done()" v-model="bill.amount" type="number" />
                        </td>
                        <td v-if="isEditing" scope="col" class="edit-col text-end">
                            <button type="button" class="btn btn-danger btn-sm" @click="deleteBill(bill.id)">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
            <div v-if="showLoading || billList.length == 0" id="data-loading" class="loader"></div>
        </div>
    </div>
</template>

<script>
    import SortThead from '../components/SortTheads.vue';

    export default {
        name: 'BillTable',
        components: {
            SortThead,

        },
        props: {
            srcBillList: [],
        },
        data() {
            return {
                showFilterCheckBox: false,
                isEditing: false,
                billList: [],
                searchStr: '',
                sortField: 'date',
                showLoading: true,
                collation: 'asc',
                filter: '全部',
                editingView: { bill: null, index: 0 },
            }
        },
        methods: {
            handleDoubleClick(bill, index) {
                if (this.isEditing && this.editingView.bill == null) {
                    this.editingView = { bill: bill, index: index };
                }
            },
            edit_done() {
                if (this.editingView.bill == null) {
                    return;
                }
                // this.$axios.post('/updateBill', this.editingView.bill)
                this.$emit('edit-bill', { ...this.editingView.bill });
                this.editingView.bill = null;
            },
            changeSort(field) {
                if (this.sortField === field) {
                    this.collation = this.collation === 'asc' ? 'desc' : 'asc';
                } else {
                    this.sortField = field;
                }
                this.sortOf(this.billList, 0, this.billList.length - 1);
                this.billList = [...this.billList];
            },
            // 排序账单
            sortOf(list, left, right) {

                if (left >= right) {
                    return;
                }
                var i = left;
                var j = right;
                var pivot = list[left]; // 存储整个对象
                while (i < j) {
                    if (this.collation === 'asc') {
                        if (this.sortField === 'date') {
                            let pivotDate = new Date(pivot.date);
                            while (new Date(list[j].date) > pivotDate && i < j) {
                                j--;
                            }
                            while (new Date(list[i].date) <= pivotDate && i < j) {
                                i++;
                            }
                        } else if (this.sortField === 'amount') {
                            while (list[j].amount > pivot.amount && i < j) {
                                j--;
                            }
                            while (list[i].amount <= pivot.amount && i < j) {
                                i++;
                            }
                        }
                    } else if (this.collation === 'desc') {
                        if (this.sortField === 'date') {
                            let pivotDate = new Date(pivot.date);
                            while (new Date(list[j].date) < pivotDate && i < j) {
                                j--;
                            }
                            while (new Date(list[i].date) >= pivotDate && i < j) {
                                i++;
                            }
                        } else if (this.sortField === 'amount') {
                            while (list[j].amount < pivot.amount && i < j) {
                                j--;
                            }
                            while (list[i].amount >= pivot.amount && i < j) {
                                i++;
                            }
                        } else {
                            return;
                        }
                    }
                    else {
                        return;
                    }
                    if (i < j) {
                        // 交换整个对象
                        var temp = list[i];
                        list[i] = list[j];
                        list[j] = temp;
                    }
                }
                // 将pivot放到正确的位置
                list[left] = list[i];
                list[i] = pivot;

                this.sortOf(list, left, i - 1);
                this.sortOf(list, i + 1, right);
            },
            deleteBill(id) {
                if (confirm('确定要删除这条记录吗？')) {
                    // 触发删除事件
                    this.$emit('delete-bill', [id]);
                }
            },
            checkAll($event) {
                if ($event.target.checked) {
                    this.billList.forEach(bill => bill.isChecked = true);
                } else {
                    this.billList.forEach(bill => bill.isChecked = false);
                }
            },
            deleteChecked() {
                if (confirm('确定要删除选中的记录吗？')) {
                    // 退出编辑模式
                    this.isEditing = false;
                    // 触发删除事件
                    this.$emit('delete-bill', this.billList.filter(bill => bill.isChecked).map(bill => bill.id));
                }
            },
            reflashData() {
                this.showLoading = true;
                setTimeout(() => {
                    this.loadData();
                    this.showLoading = false;
                }, 500);
            },
        },
        computed: {
            searchByAny() {
                return this.filteredBillList.filter(bill => {
                    return JSON.stringify(bill).includes(this.searchStr) || this.searchStr == '';
                })
            },
            filteredBillList() {
                if (this.filter === '收入') {
                    return this.billList.filter(bill => bill.type === 0);
                } else if (this.filter === '支出') {
                    return this.billList.filter(bill => bill.type === 1);
                } else {
                    return this.billList;
                }
            },
            checkedCount() {
                return this.billList.filter(bill => bill.isChecked).length;
            },
        },
        watch: {
            filter() {
                this.showFilterCheckBox = false;
            },
            srcBillList() {
                this.showLoading = true;
                setTimeout(() => {
                    this.showLoading = false;
                }, 500);
                this.billList = this.srcBillList;
            }
        },
        mounted() {
            setTimeout(() => {
                this.showLoading = false;
            }, 300);
        }
    }
</script>

<style scoped>

    .loader {
        width: 50px;
        aspect-ratio: 1;
        border-radius: 50%;
        border: 8px solid;
        border-color: #000 #0000;
        animation: l1 1s infinite;
    }

    @keyframes l1 {
        to {
            transform: rotate(.5turn)
        }
    }

    #billTable>tbody>tr {
        height: 50px;
        padding: 200px;
    }

    .table-danger.myhover:hover {
        --bs-table-bg: rgb(247, 198, 202);
    }

    .table-success.myhover:hover {
        --bs-table-bg: rgb(173, 238, 208);
    }

    .edit-input {
        border: grey solid 1px;
        border-radius: 5px;
        box-shadow: 1px 1px 1px grey;
        outline: none;
        background-color: transparent;
        width: 100%;
    }

    #billTable th {
        line-height: 100%;
        height: 30px;
    }

    .sort-btn-group {
        display: flex;

        height: 50px;
    }

    .sort-col {
        cursor: pointer;
    }

    .sort-btn-group img {
        height: 20px;
    }

    .filter-btn {
        height: 25px;
        cursor: pointer;
    }

    .filter-menu {
        position: absolute;
        left: 0;
        top: 0;
        z-index: 10;
        transform: translate(45px, 20px);
        background-color: #FFFFFF;
        border: 1px solid #CCCCCC;
        border-radius: 5px;
        box-shadow: 1px 1px 1px grey;
    }

    .filter-menu>* {
        margin: 5px;
    }

    .filter-menu {
        overflow: hidden;
        /* 防止内容溢出 */
    }

    .fade-enter-active,
    .fade-leave-active {
        transition: opacity 0.3s ease;
    }

    .fade-enter,
    .fade-leave-to

    /* .fade-leave-active 在 Vue 2 中 */
        {
        opacity: 0;
    }
</style>